// const DS_API_KEY = "sk-6f5a05ab85b2427f9e378d6062c46ed1";
// const DS_API_URL = "https://api.deepseek.com/v1/chat/completions";

const GROQ_API_KEY = "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";
const GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions";

// const SILICON_FLOW_API_KEY = "sk-arvrygykextjrjqvhsiqlmvckfyrlccaejvabliehtxxxcao"
// const SILICON_FLOW_API_URL = "https://api.siliconflow.cn/v1/chat/completions";


chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.type === 'COPIED_TEXT') {
    const copiedText = request.text;
    console.log('Background copied text saved:', copiedText);

    chrome.storage.local.get("popupWindowId", (data) => {
      if (data.popupWindowId) {
        // 如果弹窗已打开，更新存储的 LLM 响应
        chrome.storage.local.set({ llmResponse: "翻译中..." });
      } else {
        // 创建新的弹窗
        chrome.windows.create({
          url: "popup.html",
          type: "popup",
          width: 300,
          height: 350
        }, (window) => {
          if (window) {
            chrome.storage.local.set({ popupWindowId: window.id, llmResponse: "翻译中..." });
          }
        });
      }
    });

    // fetchDeepSeekResponse(copiedText)
    //   .then(responseText => {
    //     chrome.storage.local.set({ llmResponse: responseText }); // 更新 LLM 结果
    //     console.log('DeepSeek Response Saved:', responseText);
    //   })
    //   .catch(error => console.error("Error fetching DeepSeek response:", error));

    fetchGroqResponse(copiedText)
      .then(responseText => {
        chrome.storage.local.set({ llmResponse: responseText }); // 更新 LLM 结果
        console.log('Groq Response Saved:', responseText);
      })
      .catch(error => console.error("Error fetching Groq response:", error));

    /* fetchSiliconFlowResponse(copiedText)
      .then(responseText => {
        chrome.storage.local.set({ llmResponse: responseText }); // 更新 LLM 结果
        console.log('Silicon Flow Response Saved:', responseText);
      })
      .catch(error => console.error("Error fetching Silicon Flow response:", error)); */
  }
});

// 监听弹窗关闭事件，重置 popupWindowId 标志
chrome.windows.onRemoved.addListener((windowId) => {
  chrome.storage.local.get("popupWindowId", (data) => {
    if (data.popupWindowId === windowId) {
      chrome.storage.local.remove("popupWindowId");
    }
  });
});

const sys_prompt = `
你是一个翻译软件，把收到的英文翻译成中文返回。
翻译的需要按照字典格式，以词条，音标，词性，释义的顺序给出。
格式如下:
<h1 class="word">Curriculum</h1>
<p class="pronunciation">/kəˈrɪkjʊləm/</p>
<div class="part-of-speech">
  <span class="pos">n.</span>
</div>
<div class="definition">
  <ul>
    <li>1.课程；全部课程</li>
    <li>2.（学校的）必修课程</li>
    <li>3.（特定学科的）教学大纲</li>
  </ul>
</div>
`;
// 使用 fetch 调用 DeepSeek API
// async function fetchDeepSeekResponse(text) {
//   const requestBody = {
//       model: "deepseek-chat",
//       messages: [
//         { role: "system", content: sys_prompt },
//         { role: "user", content: text }
//       ]
//   };

//   try {
//       const response = await fetch(DS_API_URL, {
//           method: "POST",
//           headers: {
//               "Content-Type": "application/json",
//               "Authorization": `Bearer ${DS_API_KEY}`
//           },
//           body: JSON.stringify(requestBody)
//       });

//       const data = await response.json();
//       return data.choices?.[0]?.message?.content || "No response from DeepSeek.";
//   } catch (error) {
//       console.error("DeepSeek API request failed:", error);
//       return "Error communicating with DeepSeek.";
//   }
// }

async function fetchGroqResponse(text) {
  const requestBody = {
      model: "llama-3.3-70b-versatile",
      messages: [
        { role: "system", content: sys_prompt },
        { role: "user", content: text }
      ]
  };

  try {
      const response = await fetch(GROQ_API_URL, {
          method: "POST",
          headers: {
              "Content-Type": "application/json",
              "Authorization": `Bearer ${GROQ_API_KEY}`
          },
          body: JSON.stringify(requestBody)
      });
  
      const data = await response.json();
      return data.choices?.[0]?.message?.content || "No response from Groq.";
  } catch (error) {
      console.error("Groq API request failed:", error);
      return "Error communicating with Groq.";
  }
}


async function fetchSiliconFlowResponse(text) {
  const requestBody = {
      model: "deepseek-ai/DeepSeek-V3",
      messages: [
        { role: "system", content: "你是一个翻译软件，把收到的英文翻译成中文返回。" },
        { role: "user", content: text }
      ]
  };

  try {
      const response = await fetch(SILICON_FLOW_API_URL, {
          method: "POST",
          headers: {
              "Content-Type": "application/json",
              "Authorization": `Bearer ${SILICON_FLOW_API_KEY}`
          },
          body: JSON.stringify(requestBody)
      });

      const data = await response.json();
      return data.choices?.[0]?.message?.content || "No response from Silicon Flow.";
  } catch (error) {
      console.error("Silicon Flow API request failed:", error);
      return "Error communicating with Silicon Flow.";
  }
}
